class MyArray {

  constructor(capacity) {
    this.array = new Array(capacity);
    this.size = 0;
  }

  insert(index, element) {
    //判断访问下标是否超出范围
    if (index < 0 || index > this.size) {
      throw new Error("超出数组实际元素范围！");
    }
    //如果实际元素达到数组容量上线，数组扩容
    if (this.size >= this.array.length) {
      this.resize();
    }
    //从右向左循环，逐个元素向右挪一位。
    for (let i = this.size - 1; i >= index; i -= 1) {
      this.array[i + 1] = this.array[i];
    }
    //腾出的位置放入新元素
    this.array[index] = element;
    this.size += 1;
  }

  resize() {
    const len = this.array.length;
    this.array = [...this.array, ...new Array(len)];
  }

  delete(index) {
    let deletedElement;

    //判断访问下标是否超出范围
    if (index < 0 || index >= this.size) {
      throw new Error("超出数组实际元素范围！");
    }

    deletedElement = this.array[index];
    //从左向右循环，逐个元素向左挪一位。
    for (let i = index; i < this.size - 1; i += 1) {
      this.array[i] = this.array[i + 1];
    }

    this.size -= 1;
    return deletedElement;
  }

  output() {
    for (let i = 0; i < this.size; i += 1) {
      console.log(this.array[i]);
    }
  }
}

const myArray = new MyArray(4);
myArray.insert(0, 3);
myArray.insert(1, 7);
myArray.insert(2, 9);
myArray.insert(3, 5);
myArray.insert(1, 6);
myArray.insert(5, 8);
myArray.delete(3);
myArray.output();
